import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

// 使用动态导入实现代码分割
// 保留核心组件的静态导入以确保快速加载
import Login from '@/views/Login.vue'
import Dashboard from '@/views/Dashboard.vue'

// 业务页面使用动态导入
const RefundManagement = () => import('@/views/RefundManagement.vue')
// const RefundTaskManagement = () => import('@/views/RefundTaskManagement.vue') // 临时隐藏
const Statistics = () => import('@/views/Statistics.vue')
const Dictionary = () => import('@/views/Dictionary.vue')
const HisRefundVerify = () => import('@/views/HisRefundVerify.vue')
const RefundExportReport = () => import('@/views/RefundExportReport.vue')
const RefundTaskCompletion = () => import('@/views/RefundTaskCompletion.vue')
const TaskAdjustment = () => import('@/views/TaskAdjustment.vue')

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: Dashboard,
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'Dashboard',
        redirect: '/refund'
      },
      {
        path: '/refund',
        name: 'RefundManagement',
        component: RefundManagement
      },
      // {
      //   path: '/refund-task',
      //   name: 'RefundTaskManagement',
      //   component: RefundTaskManagement,
      //   meta: { requiresAuth: true, title: '退款任务管理' }
      // }, // 临时隐藏退款任务管理
      {
        path: '/statistics',
        name: 'Statistics',
        component: Statistics
      },
      {
        path: '/dictionary',
        name: 'Dictionary',
        component: Dictionary
      },
      {
        path: '/his-verify',
        name: 'HisRefundVerify',
        component: HisRefundVerify
      },
      {
        path: '/refund-report',
        name: 'RefundReport',
        component: () => import('@/views/RefundReport.vue'),
        meta: { requiresAuth: true, title: '退费报表管理' }
      },
      {
        path: '/refund-export-report',
        name: 'RefundExportReport',
        component: RefundExportReport,
        meta: { requiresAuth: true, title: '财务报表导出' }
      },
      {
        path: '/refund-task-completion',
        name: 'RefundTaskCompletion',
        component: RefundTaskCompletion,
        meta: { requiresAuth: true, title: '退费任务完成情况' }
      },
      {
        path: '/task-adjustment',
        name: 'TaskAdjustment',
        component: TaskAdjustment,
        meta: { requiresAuth: true, title: '工作任务调整' }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory('/his-refund/'),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  
  if (to.meta.requiresAuth && !authStore.isAuthenticated) {
    next('/login')
  } else if (to.path === '/login' && authStore.isAuthenticated) {
    next('/')
  } else {
    next()
  }
})

export default router